package com.zbkj.crmeb.order.channel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Resource;

import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.plat.by.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.crmeb.core.common.CommonResult;
import com.utils.HttpUtils;
import com.zbkj.crmeb.enums.PurchaseOrderChannelTypeEnum;
import com.zbkj.crmeb.order.AbstractStoreOrderService;
import com.zbkj.crmeb.order.StoreOrderFactory;
import com.zbkj.crmeb.order.response.LeamOrderResponse;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.vo.StoreOrderInfoVo;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class LeamStoreOrderServiceImpl extends AbstractStoreOrderService {
    @Resource
    private StoreOrderDao storeOrderDao;
    @Autowired
    StoreProductService storeProductService;
    @Autowired
    StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    StoreOrderFactory storeOrderFactory;

    /********* leam配置参数  *********/
    @Value("${leam.url}")
    private String leamUrl;
    @Value("${leam.token}")
    private String leamToken;

    @Override
    public CommonResult<Object> addChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        List<String> errorMessages = new ArrayList<>();  // 用于收集错误信息
        try {
            orderInfoVoList.forEach(order -> {
                //无推送订单号
                storeOrder.setPushOrderNo(null);
                String sourceSkuId = order.getInfo().getProductInfo().getAttrInfo().getSourceSkuId();
                if(sourceSkuId.startsWith(ProductTypeEnum.LEAM.getCode()+"-")){
                    sourceSkuId = sourceSkuId.replaceFirst(ProductTypeEnum.LEAM.getCode()+"-","");
                }
                // 组建订单对象
                String leamOrderRequest = sourceSkuId + ":" + order.getInfo().getCartNum();
                Result result = pushOrder(storeOrder, leamOrderRequest, order);
                if(result.isSuccess()){
                    errorMessages.add("订单号: " + order.getOrderInfoId() + ",错误: " + result.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!errorMessages.isEmpty()) {
            return CommonResult.failed(String.join("\n", errorMessages));
        }
        return CommonResult.success();
    }

    private Result pushOrder(StoreOrder storeOrder, String orderData, StoreOrderInfoVo orderInfo) {
    	String orderId = storeOrder.getSource() == 9 ? storeOrder.getOrderId().split("-")[0] : storeOrder.getOrderId();
        // 组装请求url
        StringBuilder sb = new StringBuilder();
        sb.append(leamUrl)
                .append("/ApiV3/token/")
                .append(leamToken)
                .append("/callType/putOrder/orderData/")
                .append(orderData);
        log.info("--------------- 开始请求LEAM创建订单url: {} ---------------", sb);
        String result = HttpUtils.sendGet(sb.toString(),null);
        log.info("--------------- 请求LEAM创建订单返回结果: {} ---------------", result);
        //处理返回结果
        Map map = (Map) JSON.parse(result);
        Map system = JSONObject.parseObject(map.get("system").toString(), Map.class);
        log.info("--------------- 请求LEAM创建订单返回system结果: [status:{}, msg:{}] ---------------", system.get("status"),system.get("msg"));
//        if (Objects.equals(system.get("status"), "error")) {
//            log.error("--------------- 请求LEAM创建订单返回system结果: {} ---------------", system.get("msg"));
//        }
        List<LeamOrderResponse> leamOrderResponseList = new ArrayList<>();
        for (Object key : map.keySet()) {
            if (!Objects.equals(key, "system")) {
                LeamOrderResponse leamOrderResponse = JSONObject.parseObject(map.get(key).toString(), LeamOrderResponse.class);
                leamOrderResponseList.add(leamOrderResponse);
            }
        }
        if (CollectionUtils.isNotEmpty(leamOrderResponseList)) {
            for (LeamOrderResponse leamOrderResponse : leamOrderResponseList) {
                if (Objects.equals(leamOrderResponse.getStatus(), "ok")) {
                    //新增采购单
                    storeOrderFactory.insertPurchaseOrder(storeOrder, true, PurchaseOrderChannelTypeEnum.LEAM.getCode());
                    //新增采购商品
                    storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, true, leamOrderResponse.getMsg(), null);
                    if (storeOrder.getPushStatus() != 2) {
                		StoreOrder storeOrderUpdate = new StoreOrder();
                		storeOrderUpdate.setId(storeOrder.getId());
                		storeOrderUpdate.setPushStatus(1);
                		storeOrderUpdate.setPushMessage("LEAM推送:" + leamOrderResponse.getMsg());
                        storeOrderDao.updateById(storeOrderUpdate);
                        log.info("--------------- 下订单成功:{},商品id:{} ---------------", leamOrderResponse.getMsg(), orderInfo.getProductId());
                    }
                }
                if (Objects.equals(leamOrderResponse.getStatus(), "error")) {
                    //新增采购单
                	storeOrderFactory.insertPurchaseOrder(storeOrder, false, PurchaseOrderChannelTypeEnum.LEAM.getCode());
                    //新增采购商品
                	storeOrderFactory.insertPurchaseGoods(orderInfo, storeOrder, false, leamOrderResponse.getMsg(), null);
            		StoreOrder storeOrderUpdate = new StoreOrder();
            		storeOrderUpdate.setId(storeOrder.getId());
            		storeOrderUpdate.setPushStatus(2);
                    storeOrderUpdate.setPushMessage(leamOrderResponse.getMsg());
                    storeOrderDao.updateById(storeOrderUpdate);
                    log.info("--------------- 下订单失败:{},商品id:{} ---------------", leamOrderResponse.getMsg(), orderInfo.getProductId());
                    return new Result(false, null, leamOrderResponse.getMsg());
                }
            }
        }
        return new Result(true);
    }

    @Override
    public CommonResult<Object> cancelChannelOrder(StoreOrder storeOrder, List<StoreOrderInfoVo> orderInfoVoList) {
        return null;
    }

    @Override
    public CommonResult<Object> getOrderInfo(String channelOrderSn) {
        return null;
    }
}
